package com.example.demo.example1.service;

import com.example.demo.example1.entity.Course;
import com.example.demo.example1.entity.Score;
import com.example.demo.example1.entity.Student;
import com.example.demo.example1.repository.ScoreRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import javax.transaction.Transactional;
import java.util.List;

/**
 * Created by pengwan on 2017/7/28.
 */
@Service
@Transactional // 保持session, 解决hibernate的懒加载异常问题
public class FetchJoinDemoService {
    @Autowired
    private ScoreRepository scoreRepository;
    public void test(){
        Specification<Score> scoreSpecification = (root, criteriaQuery, criteriaBuilder) -> {
            root.fetch(root.getModel().getSingularAttribute("student", Student.class),JoinType.INNER);
            root.fetch(root.getModel().getSingularAttribute("course", Course.class),JoinType.INNER);
            return criteriaQuery.getRestriction();
        };
        List<Score> scoreList = scoreRepository.findAll(scoreSpecification);
        System.out.print(scoreList);
    }

}
